#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
区域设置对话框，用于编辑区域参数
"""

from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QGroupBox,
    QLabel, QSpinBox, QPushButton, QCheckBox, QSlider, QLineEdit,
    QColorDialog
)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor

class RegionSettingsDialog(QDialog):
    """区域设置对话框"""

    def __init__(self, region_data=None, parent=None):
        """初始化对话框
        
        参数:
            region_data (tuple): 区域数据 (x, y, w, h, name)
            parent: 父窗口
        """
        super().__init__(parent)
        self.region_data = region_data
        self.bg_color = [0, 255, 0]  # 默认绿色背景
        self.bg_threshold = 0  # 默认阈值设为0
        self.enable_bg_removal = False  # 默认不启用背景滤除
        self.bg_removal_initialized = False  # 是否已经完成背景滤除设置
        
        # 如果提供了区域数据，解析它
        if region_data:
            if len(region_data) >= 5:
                self.name = region_data[4]
            else:
                # 如果父窗口存在，获取当前区域数并+1
                if parent and hasattr(parent, 'region_mgr'):
                    self.name = f"区域1"  # 首个区域固定为区域1
                else:
                    self.name = "区域1"
            
            # 检查是否有背景滤除属性
            if parent and hasattr(parent, 'region_mgr'):
                region_index = parent.region_mgr.get_region_index(region_data)
                if region_index >= 0:
                    bg_props = parent.region_mgr.get_region_property(region_index, "bg_removal", {})
                    self.enable_bg_removal = bg_props.get("enable", False)
                    self.bg_color = bg_props.get("color", [0, 255, 0])
                    self.bg_threshold = bg_props.get("threshold", 0)
                    self.target_color = bg_props.get("target_color", None)
                    self.bg_removal_initialized = self.enable_bg_removal  # 如果已启用，则视为已初始化
        
        # 设置窗口属性
        self.setWindowTitle("区域设置")
        self.setMinimumWidth(400)
        
        # 设置布局
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI界面"""
        layout = QVBoxLayout()
        
        # 显示当前图像文件名
        parent_widget = self.parent()
        if hasattr(parent_widget, 'region_mgr') and parent_widget.region_mgr.current_image_name:
            image_name_label = QLabel(f"当前图像: {parent_widget.region_mgr.current_image_name}")
            image_name_label.setStyleSheet("font-weight: bold; color: #0066CC;")
            layout.addWidget(image_name_label)
        
        # 坐标设置分组
        coord_group = QGroupBox("坐标设置")
        coord_layout = QGridLayout()
        
        # X坐标
        coord_layout.addWidget(QLabel("X:"), 0, 0)
        self.x_spinbox = QSpinBox()
        self.x_spinbox.setRange(0, 10000)
        self.x_spinbox.setValue(int(self.region_data[0]))  # 转换为整数
        coord_layout.addWidget(self.x_spinbox, 0, 1)
        
        # Y坐标
        coord_layout.addWidget(QLabel("Y:"), 0, 2)
        self.y_spinbox = QSpinBox()
        self.y_spinbox.setRange(0, 10000)
        self.y_spinbox.setValue(int(self.region_data[1]))  # 转换为整数
        coord_layout.addWidget(self.y_spinbox, 0, 3)
        
        # 宽度
        coord_layout.addWidget(QLabel("宽度:"), 1, 0)
        self.width_spinbox = QSpinBox()
        self.width_spinbox.setRange(1, 10000)
        self.width_spinbox.setValue(int(self.region_data[2]))  # 转换为整数
        coord_layout.addWidget(self.width_spinbox, 1, 1)
        
        # 高度
        coord_layout.addWidget(QLabel("高度:"), 1, 2)
        self.height_spinbox = QSpinBox()
        self.height_spinbox.setRange(1, 10000)
        self.height_spinbox.setValue(int(self.region_data[3]))  # 转换为整数
        coord_layout.addWidget(self.height_spinbox, 1, 3)
        
        coord_group.setLayout(coord_layout)
        layout.addWidget(coord_group)
        
        # 区域名称设置
        name_group = QGroupBox("区域名称")
        name_layout = QHBoxLayout()
        
        self.name_edit = QLineEdit(self.name)
        name_layout.addWidget(self.name_edit)
        
        name_group.setLayout(name_layout)
        layout.addWidget(name_group)
        
        # 背景滤除选项 - 简化为单个复选框
        self.bg_removal_checkbox = QCheckBox("启用背景滤除")
        self.bg_removal_checkbox.setChecked(self.enable_bg_removal)
        self.bg_removal_checkbox.toggled.connect(self.on_bg_checkbox_toggled)
        layout.addWidget(self.bg_removal_checkbox)
        
        # 按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        ok_button = QPushButton("确定")
        ok_button.clicked.connect(self.accept)
        button_layout.addWidget(ok_button)
        
        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(cancel_button)
        
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
        
    def on_bg_checkbox_toggled(self, checked):
        """背景滤除复选框状态变更处理"""
        self.enable_bg_removal = checked
        
        # 如果启用了背景滤除，立即弹出背景滤除设置对话框
        if checked and self.parent() and hasattr(self.parent(), 'original_image'):
            # 获取区域图像
            x = self.x_spinbox.value()
            y = self.y_spinbox.value()
            w = self.width_spinbox.value()
            h = self.height_spinbox.value()
            
            # 确保坐标在有效范围内
            if (0 <= x < self.parent().original_image.shape[1] and
                0 <= y < self.parent().original_image.shape[0] and
                0 < w <= self.parent().original_image.shape[1] - x and
                0 < h <= self.parent().original_image.shape[0] - y):
                
                # 提取区域图像
                region_img = self.parent().original_image[y:y+h, x:x+w].copy()
                
                # 获取区域左上角颜色作为默认待滤除颜色
                target_color = [int(c) for c in region_img[0, 0]]
                
                # 创建背景滤除对话框
                from src.ui.background_removal_dialog import BackgroundRemovalDialog
                bg_dialog = BackgroundRemovalDialog(
                    region_img,
                    self.parent(),
                    ([0, 255, 0], target_color, 0)  # 默认绿色背景，目标颜色来自图像左上角，阈值0表示默认不启用效果
                )
                
                if bg_dialog.exec_() == QDialog.Accepted:
                    # 获取背景滤除设置
                    bg_color, target_color, threshold = bg_dialog.get_settings()
                    
                    # 更新设置
                    self.bg_color = bg_color
                    self.bg_threshold = threshold
                    
                    # 标记已完成背景滤除设置
                    self.bg_removal_initialized = True
                    
                    # 如果用户设置的阈值为0，视为取消滤除
                    if threshold <= 0:
                        self.bg_removal_checkbox.setChecked(False)
                        self.enable_bg_removal = False
                        self.bg_removal_initialized = False
                else:
                    # 如果用户取消了背景滤除设置，取消勾选
                    self.bg_removal_checkbox.setChecked(False)
                    self.enable_bg_removal = False
                    self.bg_removal_initialized = False
            
    def get_settings(self):
        """获取设置
        
        返回:
            dict: 区域设置字典
        """
        return {
            "x": self.x_spinbox.value(),
            "y": self.y_spinbox.value(),
            "width": self.width_spinbox.value(),
            "height": self.height_spinbox.value(),
            "name": self.name_edit.text(),
            "enable_bg_removal": self.enable_bg_removal,
            "bg_color": self.bg_color,
            "bg_threshold": self.bg_threshold
        }
    
    def showEvent(self, event):
        """显示事件处理
        
        参数:
            event: 显示事件
        """
        super().showEvent(event)
        
        # 通知主窗口对话框已显示
        parent_widget = self.parent()
        if parent_widget is not None:
            parent_widget.dialog_active = True
            if hasattr(parent_widget, 'canvas') and hasattr(parent_widget.canvas, 'pause_suggestion'):
                parent_widget.canvas.pause_suggestion = True
    
    def closeEvent(self, event):
        """关闭事件处理
        
        参数:
            event: 关闭事件
        """
        # 通知主窗口对话框已关闭
        parent_widget = self.parent()
        if parent_widget is not None:
            parent_widget.dialog_active = False
            if hasattr(parent_widget, 'canvas') and hasattr(parent_widget.canvas, 'pause_suggestion'):
                parent_widget.canvas.pause_suggestion = False
        
        super().closeEvent(event) 